package com.xypower.tree;

import java.util.LinkedList;
//判断是否为完全二叉树
public class TestCBT {
    public static class Node {
        public int value;
        public Node left;
        public Node right;

        public Node(int data) {
            this.value = data;
        }
    }

    public static boolean isCBT(Node head){
        if (head == null){
            return true;
        }
        LinkedList<Node> queue = new LinkedList<>();
        //是否遇到过左右两个孩子不双全的结点
        boolean leaf = false;
        Node l = null;
        Node r = null;
        queue.add(head);
        while (!queue.isEmpty()){
            head = queue.poll();
            l = head.left;
            r = head.right;
            if (
                    //遇到了不双全的结点发现当前结点有孩子
                    (leaf && (l != null || r != null))
                    ||
                    (l == null && r != null)
            ){
                return false;
            }
            if (l!= null){
                queue.add(l);
            }
            if (r != null){
                queue.add(r);
            }
            if (l==null || r==null){
                leaf = true;
            }
        }
        return leaf;
    }
}
